<template>
  <el-select v-model="state.selected"
             filterable
             clearable
             :placeholder="props.placeholder"
             @change="proxy.$emit('update:modelValue',state.selected)"
             @clear="proxy.$emit('clear')"
  >
    <el-option
        v-for="(v, i) in state.data"
        :key="i"
        :value="v[props.value]"
        :label="v[props.label]"
    />
  </el-select>
</template>

<script lang="ts" setup>
import request from "/@/utils/request";
import {ref, reactive, defineProps, onMounted, getCurrentInstance, watch, onBeforeMount} from "vue";

const {proxy}: any = getCurrentInstance();
const props = defineProps({
  modelValue: String,
  url: {
    type: String,
    default: "",
  },
  value: {
    type: String,
    default: "value",
  },
  label: {
    type: String,
    default: "text",
  },
  method: {
    type: String,
    default: "get",
  },
  query: {
    type: Object,
    default: {},
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  change: {
    type: Function,
    default: () => {
    },
  },
  success: {
    type: Function,
    default: () => {
    },
  },
});

const state = reactive({
  data: [],
  selected: ""
});

const page = {
  init: async () => {
    if (proxy.$wigem.isEmpty(props.url)) {
      return;
    }

    let res: any = await request({
      url: props.url,
      method: props.method,
      params: props.query
    });
    if (res.success) {
      state.data = proxy.$wigem.isEmpty(res.data["list"]) ? res.data : res.data["list"];
      props.success(state.data);
    }
  }
}

onBeforeMount(() => {
  page.init();
})
</script>
